<template>
	<view class="page-view" v-show="isShowPage">
		<view style="height: 100%;overflow: auto;" class="box">
			<button type="primary" size="small" v-if='isShowBtn' @click="registerDevice">reload</button>
			<web-view v-if='!isShowBtn' :src="webUrl" @message="handleMessage"></web-view>
		</view>
	</view>
</template>

<script>
	import {
		getXym
	} from "@/api/common.js"
	export default {
		data() {
			return {
				webUrl: '',
				serPhone: "09999466436", //客服电话
				paramsUrl: "", //入参链接
				timer:0,
				reward:0,
				isShowBtn:false,
				isShowPage:false
			};
		},
		onShow() {
			let cToken = uni.getStorageSync('cToken') || ""
			let webUrl = uni.getStorageSync('webUrl'); //默认先取缓存中存储的上次可以访问的域名
			this.paramsUrl = webUrl || this.COFIG?.staticUrl;
			if(cToken){
				this.domainVisit(1)
			}
			else{
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/login/login'
					})
				}, 1000)
			}
		},
		
		onHide(){
			this.isShowPage = false;
			this.isShowBtn = true;
		},
		
		onUnload(){
			this.isShowPage = false;
			this.isShowBtn = true;
		},
		onTabItemTap(){
			this.renderView()
		},
		
		onReady(){
			this.renderView()
		},
		methods: {
			handleMessage(evt) {
				let obj = evt?.detail?.data;
				if (obj[0].action == "call") {
					try {
						uni.makePhoneCall({
							phoneNumber: obj[0]?.value
						});
					} catch (e) {

					}
				}
				if(obj[0].action == "home"){//返回首页
					uni.switchTab({
						url: '/pages/home/index'
					});
				}
				if(obj[0].action == "rewards"){//返回优惠券页面
					this.reward = obj[0]?.value;
					uni.reLaunch({
						url: '/pages/rewards/index'
					});
				}
				if(obj[0].action == "toLogin"){
					uni.removeStorageSync("cToken");
					uni.reLaunch({
						url:'/pages/login/login',
						animationType: 'pop-in',
						animationDuration: 200
					})
				}
			},

			//判断当前webview加载链接是否可以正常访问
			domainVisit(count) {
				let self = this;
				uni.showLoading({
					title: 'loading',
					mask: true
				})
				uni.request({
					url: this.paramsUrl,
					timeout: 10000,
					success: (response) => {
						this.isShowBtn = false;
						uni.setStorageSync('serPhone', this.serPhone);
						uni.setStorageSync('webUrl', this.paramsUrl);
						const cToken = uni.getStorageSync('cToken');
						const cTime = uni.getStorageSync('cTime');
						const deviceId = uni.getStorageSync('deviceId');
						const lastStr = this.paramsUrl.slice(-1);//判断域名是否带斜杠/
						let homePage = lastStr == "/" ? "index.html" : "/index.html"
						this.webUrl = this.paramsUrl + homePage + '?cToken=' + encodeURIComponent(cToken) +'&cTime=' + cTime+'&deviceId=' + deviceId+'&phone=' + this.serPhone+'&tab=1&reward='+this.reward+'&t=' + new Date().getTime()
						this.isShowPage = true;
						uni.hideLoading()
					},
					fail: (error) => {
						console.log('域名无法访问', error);
						if (count == "1") { //第一次判断域名是否可以访问
							this.registerDevice()
						} else { //第二次无法访问
							this.isShowBtn = true;
							this.isShowPage = true;
							uni.hideLoading()
							
						}
					},
				});
				
			},

			//获取新的域名和客服电话
			registerDevice() {
				const params = {
					ym: this.paramsUrl,
					deviceId: uni.getStorageSync("deviceId")
				}
				getXym(params).then(res => {
					if (res.code == '0000') {
						this.serPhone = res?.data?.kfdh;
						this.paramsUrl = res?.data?.xym;
						this.domainVisit(2)
					} else {
						this.timer ++ 
						if(this.timer < 6){
							this.registerDevice()
						}else{
							this.UTILS.logStr(res.message || "system error");
							uni.removeStorageSync("cToken");
							setTimeout(() => {
								uni.reLaunch({
									url:'/pages/login/login',
									animationType: 'pop-in',
									animationDuration: 200
								})
							}, 1000)
						}
					}
				})
			},
			renderView(){
				let height = 0; //定义动态的高度变量
				let statusbar = 0; // 动态状态栏高度
				let safeAreaBottom = 0
				uni.getSystemInfo({ // 获取当前设备的具体信息
					success: (sysinfo) => {
						statusbar = sysinfo.statusBarHeight;
						height = sysinfo.windowHeight;
						safeAreaBottom = sysinfo.safeAreaInsets?.bottom;
					}
				});
				let currentWebview = this.$scope.$getAppWebview(); //获取当前web-view
				setTimeout(function() {
					var wv = currentWebview.children()[0];
					wv.setStyle({ //设置web-view距离顶部的距离以及自己的高度，单位为px
						top: statusbar, //此处是距离顶部的高度，应该是你页面的头部
						height: height - statusbar - safeAreaBottom, //webview的高度,减去状态栏,减去底部安全区域
					})
				}, 500); //如页面初始化调用需要写延迟
			}
		},
	};
</script>

<style scoped lang="scss">
	.page-view{
		width: 100%;
		overflow-y: auto;
		overflow-x: hidden;
		height: 100%;
		.nav-bar {
			background-color: #F6F6F6;
		}
		.box{
			height: 100%;
			position: relative;
			button{
				width: 70%;
				margin: 400rpx auto 0 auto;
			}
		}
	}
</style>